//
//  Data+Extension.swift
//  Library_y
//
//  Created by JC on 2023/6/6.
//

import Foundation

public extension Data {
    
    // Data转字节数组
    var toBytes: [UInt8] {
        return [UInt8](self)
    }
    
    // Data进行mac格式化
    var macAddressFormat: String {
        return self.toBytes
            .map { String(format: "%02x", $0).lowercased() }
            .joined(separator: ":")
    }
    
    // Data转int
    var toInt: Int {
        let bytes = self.toBytes
        var result = 0
        for byte in bytes {
            result += Int(String(byte, radix: 10)) ?? 0
        }
        return result
    }
    
    // Data转字符串
    var toHex: String {
        return self.toBytes
            .map { String(format: "%02x", $0).uppercased() }
            .joined(separator: "")
    }
    
    // Data转字符串
    var toString: String {
        return self.toBytes
            .map { String(format: "%02x", $0).uppercased() }
            .joined(separator: " ")
    }
}

public extension Data {

    // 写入缓存文件
    func write(withName name: String) -> URL {
        let url = URL(fileURLWithPath: Caches).appendingPathComponent(name)
        let fileManager = FileManager.default
        if fileManager.fileExists(atPath: url.path) {
            try? fileManager.removeItem(atPath: url.path)
        }
        try! write(to: url, options: .atomicWrite)
        return url
    }
}
